package com.atguigu.guli.service.edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.guli.service.edu.entity.ExcelSubjectData;
import com.atguigu.guli.service.edu.entity.Subject;
import com.atguigu.guli.service.edu.mapper.SubjectMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author lsystart
 * @create2021-11-01 19:35
 */
@Slf4j
@AllArgsConstructor
@NoArgsConstructor
public class ExcelSubjectDataListener extends AnalysisEventListener<ExcelSubjectData> {

    private SubjectMapper subjectMapper ;

    @Override
    public void invoke(ExcelSubjectData excelSubjectData, AnalysisContext analysisContext) {
        String levelOneTitle = excelSubjectData.getLevelOneTitle();
        String levelTwoTitle = excelSubjectData.getLevelTwoTitle();
        log.info("一级目录: " + levelOneTitle);
        log.info("二级目录: " + levelTwoTitle);
        //扫描出的一级目录存到数据库
        LambdaQueryWrapper<Subject> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Subject::getTitle,levelOneTitle)
                .eq(Subject::getParentId,"0");
        Subject subject = subjectMapper.selectOne(queryWrapper);
        if(subject==null){
            subject = new Subject();
            subject.setTitle(levelOneTitle);
            subject.setSort(0);
            subject.setParentId("0");
            subjectMapper.insert(subject);
        }
        queryWrapper.clear();
        queryWrapper.eq(Subject::getTitle,levelTwoTitle)
                .eq(Subject::getParentId,subject.getId());
        if(subjectMapper.selectCount(queryWrapper)==0){
            Subject levelTwoSubject = new Subject();
            levelTwoSubject.setSort(0);
            levelTwoSubject.setTitle(levelTwoTitle);
            levelTwoSubject.setParentId(subject.getId());
            subjectMapper.insert(levelTwoSubject);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        System.out.println("解析完成");
    }
}
